package com.dhcc.DRGsHosp.facade.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;

import javax.inject.Named;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openkoala.koala.commons.InvokeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.FieldMapApplication;
import com.dhcc.DRGsHosp.facade.FieldMapFacade;
import com.dhcc.DRGsHosp.infra.util.ExcelUtil;
import com.dhcc.DRGsHosp.infra.util.StringUtils;

/**
 * 
 * @ClassName: FieldMapFacadeImpl  
 * @Description ：    
 * @Date: 2018年1月22日 下午9:01:17  
 * @Author mazhaoyan 
 * @Version 2.5.0 DHC-DRGs
 */
@Named("drgsHospFacadeImplMzy180122")
public class FieldMapFacadeImpl implements FieldMapFacade {
	private static final Logger LOGGER = LoggerFactory.getLogger(FieldMapFacadeImpl.class);
	@Autowired 
	private FieldMapApplication fieldMapApplication;
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FieldMapFacade#importMrData(java.lang.String)  
	 */
	@Override
	public InvokeResult parseData(String filePath,String fileType,String repeateNode) {
		if("".equals(fileType)){
			return InvokeResult.failure("请选择文件类型!");
		}else if("xmlFile".equals(fileType)&&!StringUtils.hasLength(repeateNode)){
			return InvokeResult.failure("配置xml文件时请选择重复路径!");
		}
		FileInputStream fileInputStream = null;
		String extension=filePath.substring(filePath.lastIndexOf("."));//扩展名
		try {
			fileInputStream = new FileInputStream(filePath);
			Workbook workbook=null;
			Sheet sheet=null;
			Row row=null;
			if (extension.equals(".xls")) {
				workbook=new HSSFWorkbook(fileInputStream);
				sheet=(HSSFSheet) workbook.getSheetAt(0);
			} else if(extension.equals(".xlsx")){
				workbook=new XSSFWorkbook(fileInputStream);
				sheet=(XSSFSheet)workbook.getSheetAt(0);
			}else {
				LOGGER.error("文件类型有误,只能解析Excel文件");
				return InvokeResult.failure("文件类型有误,只能解析Excel文件");
			}			
			if(StringUtils.hasLength(repeateNode)){
				Properties prop = new Properties();   
				InputStream fis = null;
				OutputStream fos = null;
				File file = new File(FieldMapFacadeImpl.class.getResource("/").getPath() + "nodeconfig.properties");
				fis = new FileInputStream(file);
				prop.load(new InputStreamReader(FieldMapFacadeImpl.class.getClassLoader().getResourceAsStream("/nodeconfig.properties"), "UTF-8"));
				fis.close();
				fos = new FileOutputStream(file);
	            prop.setProperty("mr_node_address", repeateNode);   
	            prop.store(fos,"nodeset");
	            fos.close();
			}
			StringBuilder saveSql =  new StringBuilder();
			saveSql.append("declare cnt INTEGER; begin \n");		
			for (int numRows = 1; numRows <= sheet.getLastRowNum(); numRows++) {
				row = sheet.getRow(numRows);
				String tableCode = ExcelUtil.getCellValue(row.getCell(0));
				String fieldCode = ExcelUtil.getCellValue(row.getCell(1));
				String titleName = ExcelUtil.getCellValue(row.getCell(2));
				String dataFormate = ExcelUtil.getCellValue(row.getCell(3));
				String fieldType = ExcelUtil.getCellValue(row.getCell(4));
				String fieldOrder = ExcelUtil.getCellValue(row.getCell(5));
				String fieldDesc = ExcelUtil.getCellValue(row.getCell(6));
				titleName = (titleName==null?"":titleName);
				titleName=titleName.replace("'", "''");
				
				tableCode = (tableCode == null?"":tableCode);
				tableCode=tableCode.replace("'", "''");
				
				fieldCode = (fieldCode == null?"":fieldCode);
				fieldCode=fieldCode.replace("'", "''");
				
				fieldType = (fieldType == null?"":fieldType);
				fieldType=fieldType.replace("'", "''");
				
				fieldOrder = (fieldOrder == null?"":fieldOrder);
				fieldOrder=fieldOrder.replace("'", "''");
				
				dataFormate = (dataFormate == null?"":dataFormate);
				dataFormate=dataFormate.replace("'", "''");
				
				fieldDesc = (fieldDesc == null?"":fieldDesc);
				fieldDesc=fieldDesc.replace("'", "''");
				if(StringUtils.hasLength(titleName)&&StringUtils.hasLength(fieldCode)){
					StringBuilder lineSql = new StringBuilder();
					lineSql.append(" select count(*) into cnt from drgs.t_field_map fm \n");
					lineSql.append(" where fm.file_type = '"+fileType+"' and fm.title_name = '"+titleName+"' \n");
					lineSql.append(" and fm.field_code = '"+fieldCode+"' and fm.table_code = '"+tableCode+"' ; \n");
					lineSql.append(" if cnt = 0 then \n");
					lineSql.append(" insert into drgs.t_field_map (file_type,data_format,TITLE_NAME,TABLE_CODE,FIELD_CODE,FIELD_TYPE,FIELD_ORDER,TITLE_DESC) \n");
					lineSql.append(" values ('"+fileType+"','"+dataFormate+"','"+titleName+"','"+tableCode+"','"+fieldCode+"','"+fieldType+"','"+fieldOrder+"','"+fieldDesc+"');  \n ");
					lineSql.append(" else \n ");
					lineSql.append(" update drgs.t_field_map fm set fm.TABLE_CODE = '"+tableCode+"', fm.FIELD_TYPE = '"+fieldType+"', fm.FIELD_ORDER = '"+fieldOrder+"' ,fm.data_format = '"+dataFormate+"' ,fm.TITLE_DESC='"+fieldDesc+"' \n ");
					lineSql.append(" where   fm.file_type = '"+fileType+"' and fm.TITLE_NAME = '"+titleName+"' and fm.FIELD_CODE = '"+fieldCode+"' and fm.table_code = '"+tableCode+"'  ; \n ");
					lineSql.append(" end if; \n ");
					saveSql.append(lineSql.toString());
				}
			}
			saveSql.append("commit; \n ");
			saveSql.append("end; \n ");
			fieldMapApplication.saveTableFiled(saveSql);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
			return InvokeResult.failure(e.getMessage());
		}
		return InvokeResult.success();
	}
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FieldMapFacade#getTableData()  
	 */
	@Override
	public InvokeResult getTableData(String fileType) {
		return InvokeResult.success(fieldMapApplication.getTableData(fileType));
	}
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FieldMapFacade#saveSingleField(java.util.Map)  
	 */
	@Override
	public InvokeResult saveSingleField(Map<String, Object> mapInfo) {
		try {  
			String repeatNode=mapInfo.get("repeatNode")+"";
			Properties prop = new Properties();   
			InputStream fis = null;
			OutputStream fos = null;
			File file = new File(FieldMapFacadeImpl.class.getResource("/").getPath() + "nodeconfig.properties");
			fis = new FileInputStream(file);
			prop.load(new InputStreamReader(FieldMapFacadeImpl.class.getClassLoader().getResourceAsStream("/nodeconfig.properties"), "UTF-8"));
			fis.close();
			fos = new FileOutputStream(file);
            prop.setProperty("mr_node_address", repeatNode);   
            prop.store(fos,"nodeset");
            fos.close();
			fieldMapApplication.saveSingleField(mapInfo);
		}catch (IOException e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
			return InvokeResult.failure(e.getMessage());
		}
		return InvokeResult.success();
	}
	/**  
	 * 
	 *  @Description：删除映射
	 *  @Author：liuhongjun 
	 *  @see com.dhcc.DRGsHosp.facade.FieldMapFacade#deleteFieldMap(java.util.Map)
	 */
	@Override
	public InvokeResult deleteFieldMap(Map<String, Object> mapInfo) {
		try {
			fieldMapApplication.deleteFieldMap(mapInfo);
		}catch (Exception e) {
			return InvokeResult.failure(e.getMessage());
		}
		return InvokeResult.success();
	}
	
}